﻿angular
    .module('Stackoverflow', [
        'ui.router', 'ngAnimate', 'chieffancypants.loadingBar', 'ui.select2',
        'restangular', 'ngTable', 'xeditable', 'toaster','Stackoverflow.Constants',
        'ui.bootstrap', 'ui.keypress', 'angularFileUpload'
    ])
    .config(function ($provide, $stateProvider, $urlRouterProvider, RestangularProvider, datepickerPopupConfig) {

        'use strict';

        RestangularProvider.setDefaultHttpFields({
            withCredentials: true
        });

        $provide.decorator('$state', function ($delegate, $stateParams) {
            $delegate.forceReload = function () {
                return $delegate.go($delegate.current, $stateParams, {
                    reload: true,
                    inherit: false,
                    notify: true
                });
            };
            return $delegate;
        });

        RestangularProvider
            .setBaseUrl('api/')
            .setErrorInterceptor(function (response) {
                console.log(response);
                if (response.status == 401) {
                    alert('You are not allowed to access this page');
                }
            })
            .addResponseInterceptor(function (responseData, operation, what, url, response) {
                var extractedData = responseData;

                if (operation === "getList") {
                    extractedData.total = parseInt(response.headers().total, 10);
                }

                return extractedData;
            });

        $urlRouterProvider.otherwise('/questions');

        $stateProvider
           .state('questions', {
               url: '/questions',
               templateUrl: '/Scripts/app/views/questions.html',
               controller: 'QuestionController'
           })
            .state('question-item', {
                url: '/question-item/{id}',
                templateUrl: '/Scripts/app/views/question-item.html',
                controller: 'QuestionItemController'
            })
           .state('question-detail', {
               url: '/question-detail/{id}',
               templateUrl: '/Scripts/app/views/question-detail.html',
               controller: 'QuestionDetailController'
           })
        ;
    })
    .run(function (editableOptions, $httpBackend, $rootScope, $window, $timeout) {
        'use strict';

        editableOptions.theme = 'bs3';

        $rootScope.back = function () {
            history.back();
        };

        $rootScope.doPrint = function () {
            $rootScope.title = '';
            $timeout(function () {
                $window.print();
                location.reload();
            });
        };
    })
    .filter('ordinal', function () {
        return function (input) {
            return input.charAt(0).toUpperCase() + input.substr(1).replace(/[A-Z]/g, ' $&');
        }
    });
